package random.fox.p2p.ui.customview;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.List;

import random.fox.p2p.R;
import random.fox.p2p.bean.Dynamic;


/**
 * Created by delong on 2015/3/19.
 */
public class DynamicAdapter extends BaseAdapter {

    protected ImageLoader imageLoader = ImageLoader.getInstance();
    DisplayImageOptions options;
    private Context context;
    private List<Dynamic> list;
    private int itemWidth;

    private int temp;
    private boolean isExpand;

    public DynamicAdapter(List<Dynamic> list, int itemWidth, int temp, boolean isExpand) {
        this.list = list;
        this.itemWidth = itemWidth;
        this.temp = temp;
        this.isExpand = isExpand;
        // 使用DisplayImageOptions.Builder()创建DisplayImageOptions
        options = new DisplayImageOptions.Builder().showImageOnLoading(R.mipmap.ic_launcher)
                .showImageForEmptyUri(R.mipmap.ic_launcher)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.ic_launcher)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();
    }

    @Override
    public int getCount() {
        int count = 0;
        if (isExpand) {
            count = temp;
        } else {
            count = list.size();
        }
        Log.d("DynamicAdapter", count + "");
        return count;
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(context==null)
            context = parent.getContext();
        ImageView imageView = new ImageView(context);
        imageView.setLayoutParams(new AbsListView.LayoutParams(itemWidth, itemWidth));
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        if (isExpand && position == temp - 1) {
            imageLoader.displayImage("drawable://" + R.drawable.expand, imageView, options);
        } else {
            String url = list.get(position).getUrls().get(0);
            imageLoader.displayImage(url, imageView, options);
        }
        return imageView;
    }
}
